import { createSlice, createAsyncThunk, PayloadAction } from '@reduxjs/toolkit';
import axios from 'axios';

/** API基础URL配置 */
const API_BASE_URL = process.env.REACT_APP_API_BASE_URL || 'http://localhost:5197';

/**
 * 城市信息接口
 *
 * 表示城市的基本信息和地理位置
 */
interface City {
  /** 城市ID */
  id: string;
  /** 城市名称 */
  name: string;
  /** 国家名称 */
  country: string;
  /** 纬度 */
  latitude: number;
  /** 经度 */
  longitude: number;
  /** 时区 */
  timeZone: string;
  /** 是否活跃 */
  isActive: boolean;
}

/**
 * 城市状态管理接口
 *
 * 管理城市列表、选中状态、加载状态等
 */
interface CityState {
  /** 城市列表 */
  cities: City[];
  /** 加载状态 */
  loading: boolean;
  /** 错误信息 */
  error: string | null;
  /** 当前选中的城市ID */
  selectedCityId?: string;
}

/**
 * 初始状态
 */
const initialState: CityState = {
  cities: [],
  loading: false,
  error: null,
  selectedCityId: undefined,
};

/**
 * 异步Action：获取城市列表
 *
 * 从后端API获取所有城市信息
 */
export const fetchCitiesAsync = createAsyncThunk(
  'city/fetchCities',
  async () => {
    const response = await axios.get(`${API_BASE_URL}/api/weather/cities`);
    return response.data;
  }
);

/**
 * 异步Action：创建城市
 *
 * 添加新的城市到系统
 */
export const createCityAsync = createAsyncThunk(
  'city/createCity',
  async (cityData: Omit<City, 'id'>) => {
    const response = await axios.post(`${API_BASE_URL}/api/weather/cities`, cityData);
    return response.data;
  }
);

/**
 * 异步Action：更新城市信息
 *
 * 更新指定城市的基本信息
 */
export const updateCityAsync = createAsyncThunk(
  'city/updateCity',
  async (params: { id: string; cityData: Partial<City> }) => {
    const response = await axios.put(`${API_BASE_URL}/api/weather/cities/${params.id}`, params.cityData);
    return { id: params.id, ...params.cityData };
  }
);

/**
 * 异步Action：删除城市
 *
 * 从系统中删除指定城市
 */
export const deleteCityAsync = createAsyncThunk(
  'city/deleteCity',
  async (cityId: string) => {
    await axios.delete(`${API_BASE_URL}/api/weather/cities/${cityId}`);
    return cityId;
  }
);

/**
 * 异步Action：切换城市状态
 *
 * 启用或禁用指定城市的数据采集功能
 */
export const toggleCityStatusAsync = createAsyncThunk(
  'city/toggleStatus',
  async (params: { cityId: string; isActive: boolean }) => {
    await axios.patch(`${API_BASE_URL}/api/weather/cities/${params.cityId}/status`, {
      isActive: params.isActive
    });
    return params;
  }
);

/**
 * 城市状态管理Slice
 *
 * 管理城市相关的状态和CRUD操作
 */
const citySlice = createSlice({
  name: 'city',
  initialState,
  reducers: {
    /** 设置选中的城市ID */
    setSelectedCityId: (state, action: PayloadAction<string | undefined>) => {
      state.selectedCityId = action.payload;
    },
    /** 清除错误信息 */
    clearError: (state) => {
      state.error = null;
    },
  },
  extraReducers: (builder) => {
    builder
      // 获取城市列表状态处理
      .addCase(fetchCitiesAsync.pending, (state) => {
        state.loading = true;
        state.error = null;
      })
      .addCase(fetchCitiesAsync.fulfilled, (state, action) => {
        state.loading = false;
        state.cities = action.payload;
      })
      .addCase(fetchCitiesAsync.rejected, (state, action) => {
        state.loading = false;
        state.error = action.error.message || '获取城市列表失败';
      })
      // 创建城市状态处理
      .addCase(createCityAsync.fulfilled, (state, action) => {
        state.cities.push(action.payload);
      })
      .addCase(createCityAsync.rejected, (state, action) => {
        state.error = action.error.message || '创建城市失败';
      })
      // 更新城市状态处理
      .addCase(updateCityAsync.fulfilled, (state, action) => {
        const index = state.cities.findIndex(city => city.id === action.payload.id);
        if (index !== -1) {
          state.cities[index] = { ...state.cities[index], ...action.payload };
        }
      })
      .addCase(updateCityAsync.rejected, (state, action) => {
        state.error = action.error.message || '更新城市失败';
      })
      // 删除城市状态处理
      .addCase(deleteCityAsync.fulfilled, (state, action) => {
        state.cities = state.cities.filter(city => city.id !== action.payload);
      })
      .addCase(deleteCityAsync.rejected, (state, action) => {
        state.error = action.error.message || '删除城市失败';
      })
      // 切换城市状态状态处理
      .addCase(toggleCityStatusAsync.fulfilled, (state, action) => {
        const city = state.cities.find(c => c.id === action.payload.cityId);
        if (city) {
          city.isActive = action.payload.isActive;
        }
      })
      .addCase(toggleCityStatusAsync.rejected, (state, action) => {
        state.error = action.error.message || '切换城市状态失败';
      });
  },
});

export const { setSelectedCityId, clearError } = citySlice.actions;
export default citySlice.reducer;